<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <script src="/houtai/js/vue.js"></script>
    <script type="text/javascript" src="/houtai/js/jquery-2.1.4.js"></script>

    <link rel="stylesheet" href="/houtai/layuiadmin/layui/css/layui.css"  media="all">
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->

</head>
<body>

<!--------------------------------------头部工具条------------------------------------------>
<script type="text/html" id="headbar">
    <div class="layui-btn-container"  >
        <!--使用表达式让按钮动态显示，if条件为true则显示，false不显示-->
        <!--{{#  if(insert){ }}-->
        <!--<button type="button" class="layui-btn" lay-event="insert">增加-->
            <!--<i class="layui-icon">&#xe654;</i>-->
        <!--</button>-->
        <!--{{#  } }}-->

        <!--判断是否有删除权限-->
        {{#  if(del){ }}
        <button class="layui-btn layui-btn-danger" lay-event="getCheckData">批量删除
            <i class="layui-icon">&#xe640;</i>
        </button>
        {{#  } }}
    </div>
</script>

<!-------------------------------------------- 每一行工具条 --------------------------------------->
<script type="text/html" id="barDemo">
    <!--判断是否有修改权限-->
    {{#  if(update){ }}
    <button type="button" class="layui-btn layui-btn-xs layui-btn-radius layui-btn-warm" lay-event="singleUpdate">
        <i class="layui-icon">&#xe642;</i> 修改
    </button>
    {{#  } }}

    <!--判断是否有删除权限-->
    {{#  if(del){ }}
    <button type="button" class="layui-btn layui-btn-xs layui-btn-radius layui-btn-danger" lay-event="singleDel">
        <i class="layui-icon">&#xe640;</i> 删除
    </button>
    {{#  } }}
</script>

<!----------------------------------------头部工具条获取复选框数据,未开启----------------------------------->
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
        <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
        <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
    </div>
</script>

<!---------------------------------------------条件搜索框------------------------------------------->
<div class="demoTable" style="margin-top: 10px">
    <form id="serachForm" class="layui-form">
        订单编号：
        <div class="layui-inline">
            <input class="layui-input" name="myorderNumber" id="myorderNumber" autocomplete="off">
        </div>
        下单人：
        <div class="layui-inline" style="width: 100px">
            <input class="layui-input" id="username" name="username" autocomplete="off">
        </div>
        <div class="layui-form-item" style="width: 200px;float: left;margin-right: 10px">
            <label class="layui-form-label">订单状态</label>
            <div class="layui-input-block">
                <select name="orderStatus" id="orderStatus" lay-filter="aihao">
                    <option value="0" selected></option>
                    <option value="1" >待付款</option>
                    <option value="2">已发货</option>
                    <option value="3">已完成</option>
                    <option value="4">音乐</option>
                    <option value="5">退单</option>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">下单日期</label>
            <div class="layui-input-inline" style="width: 100px">
                <input type="text" name="startDate" id="startDate" lay-verify="date" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
            </div>
            -
            <div class="layui-input-inline" style="width: 100px">
                <input type="text" name="endDate" id="endDate" lay-verify="date" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline" style="margin-left: 10px">
            <!--这个地方的不能直接使用button标签，使用button标签会重复提交数据-->
            <input type="button" class="layui-btn" data-type="reload" value="搜索">
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>

    </form>
</div>

<!-----------------------------------------表格内容--------------------------------------------->
<div id="content">
    <table class="layui-table"
           lay-data="{url:'/houtai/page/order/list',page:true,limit:10,limits:[10,20,10000],toolbar:'#headbar',
                     height:'full-100',totalRow:true,loading:true,title:'用户信息表',
                     //把返回的数据result转为换layUI需要的格式，此处返回的是mybatisPlus的IPage对象，具体返回值自己设定
                     parseData: function(res){ //res 即为原始返回的数据
                        return {
                            'code': res.code, //解析接口状态
                            'msg': res.message, //解析提示文本
                            'count': res.obj.totalSize, //解析数据长度
                            'data': res.li //解析数据列表
                          };
                       },
                //给表格设置一个ID
               id:'test'}"
           lay-filter="filter">
        <thead>
        <tr>
            <!--开起全选框-->
            <th lay-data="{checkbox:true,fixed:'left'}"></th>
            <th lay-data="{field:'myorderId',fixed:'left',hide:true}">订单ID</th>
            <!--把订单编号作为合计行标题-->
            <th lay-data="{field:'myorderNumber',minWidth:110,totalRowText:'合计',fixed:'left'}">订单编号</th>
            <!--返回对象中另一个对象的属性-->
            <th lay-data="{field:'user',
                templet:function (d) {
                    return d.user.username;
                }
            }">下单人</th>
            <!--判断-->
            <th lay-data="{field:'orderStatus',minWidth:110,sort: true,
                templet:function (d) {
                    if(d.orderStatus == 1){
                        return '待付款';
                    }else if(d.orderStatus == 2){
                        return '已发货';
                    }else if(d.orderStatus == 3){
                        return '已完成';
                    }else if(d.orderStatus == 4){
                        return '音乐';
                    }else if(d.orderStatus == 3){
                        return '退单';
                    }

                }
            }">订单状态</th>
            <!--<th lay-data="{field:'orderTime',sort: true,-->
                <!--templet:function (d) {-->
                    <!--return timeFormat(d.orderTime);-->
                <!--}-->
               <!--}">下单时间</th>-->
            <th lay-data="{field:'orderTime',sort: true}">下单时间</th>
            <th lay-data="{field:'totalPrice',minWidth:110,  totalRow: true,sort: true}">订单总价</th>
            <th lay-data="{field:'userAddress',minWidth:110,
                templet:function (d) {
                    return d.userAddress.name;
                }
            }">收件人</th>
            <th lay-data="{field:'userAddress',minWidth:110,
                templet:function (d) {
                    return d.userAddress.tel;
                }
            }">收件人电话</th>
            <th lay-data="{field:'userAddress',minWidth:110,
                templet:function (d) {
                    return d.userAddress.addr;
                }
            }">收货地址</th>
            <!--orderIntegral-->
            <th lay-data="{field:'orderIntegral',minWidth:110}">订单积分</th>
            <!--最后一列操作列，有修改或删除的权限就显示这列，否者不显示，通过Vue实现-->
            <th v-if="isShow" lay-data="{field:'opeartion', width:170,fixed: 'right', toolbar: '#barDemo'}">操作</th>
        </tr>
        </thead>
    </table>
</div>

<!-----------这里是修改弹出层的表单信息,表单的id用于表单的选择，style是在本页隐藏，只有点击编辑才会弹出---------->
<div class="layui-row" id="popUpdateUser" style="display:none;">
    <form class="layui-form" id="updateForm" lay-filter="updateFormFilter">
        <input name="myorderId" hidden>
        <input name="myorderNumber" hidden>
        <input name="userId" hidden>
        <input name="orderTime" hidden>
        <input name="totalPrice" hidden>
        <input name="userAddressId" hidden>
        <div class="layui-form-item" style="width: 350px;margin-top: 10px;margin-left: 30px">
            <label class="layui-form-label">订单状态</label>
            <div class="layui-input-block">
                <select name="orderStatus" id="updateOrderStatus" lay-filter="aihao">
                    <option value="1">待付款</option>
                    <option value="2">已发货</option>
                    <option value="3">已完成</option>
                    <option value="4">音乐</option>
                    <option value="5">退单</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item" style="width: 350px;margin-top: 10px;margin-left: 30px">
            <label class="layui-form-label">收件人</label>
            <div class="layui-input-block">
                <input type="text" name="name" id="name" required  lay-verify="required" placeholder="请输入收件人姓名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" style="width: 350px;margin-top: 10px;margin-left: 30px">
            <label class="layui-form-label">收件人电话</label>
            <div class="layui-input-block">
                <input type="text" name="tel" id="tel" required  lay-verify="required" placeholder="请输入收件人电话" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" style="width: 350px;margin-top: 10px;margin-left: 30px">
            <label class="layui-form-label">收件人地址</label>
            <div class="layui-input-block">
                <input type="text" name="addr" id="addr" required  lay-verify="required" placeholder="请输入收件人地址" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" style="margin-top: 50px">
            <div class="layui-input-block">
                <input type="button" class="layui-btn" lay-submit lay-filter="updateSubmit" value="立即提交">
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>

<script src="/houtai/layuiadmin/layui/layui.js" charset="utf-8"></script>
<script src="/houtai/layuiadmin/layui/lay/modules/util.js" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 -->

<!--转换时间格式、数字转字符串-->
<script type="text/javascript">
    /**
     * 将"2018-05-19T08:04:52.000+0000"这种格式的时间转化为正常格式\
     */
    function timeFormat(time) {
        var d = new Date(time);

        var year = d.getFullYear();       //年
        var month = d.getMonth() + 1;     //月
        var day = d.getDate();            //日

        var hh = d.getHours();            //时
        var mm = d.getMinutes();          //分
        var ss = d.getSeconds();           //秒

        var clock = year + "/";

        if (month < 10)
            clock += "0";

        clock += month + "/";

        if (day < 10)
            clock += "0";

        clock += day + " ";

        if (hh < 10)
            clock += "0";

        clock += hh + ":";
        if (mm < 10) clock += '0';
        clock += mm + ":";

        if (ss < 10) clock += '0';
        clock += ss;
        return (clock);
    };
</script>
<script>

    //定义四个全局变量用于是否显示增加、删除、修改按钮的权限验证
    var insert = false;//是否具备新增权限，默认不具备
    var del= false;
    var update= false;
    var isShow=false;
    //利用Vue判断是否具备每一行的删除或者修改权限
    var vue = new Vue({
        el:"#content",
        data:{
            buttons:[]
        },
        computed:{
            isShow:function () {
                var _this = this;
                var delbtn=false;
                var updatebtn=false;
                //获取当前网页地址
                var url = location.href.split("localhost:8080")[1];
                $.ajax({
                    url: "/houtai/adminuser/buttons",
                    type: "get",
                    async: false,
                    data: {
                        url: url
                    },
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                        _this.buttons = data.li;
                        for(var i=0;i<_this.buttons.length;i++){
                            if(_this.buttons[i].menuUrl.indexOf("insert")!=-1){
                                insert = true;
                                break;
                            }
                        }
                        for(var i=0;i<_this.buttons.length;i++){
                            if(_this.buttons[i].menuUrl.indexOf("delete")!=-1){
                                del = true;
                                isShow = true;
                                delbtn = true;
                                break;
                            }
                        }
                        for(var i=0;i<_this.buttons.length;i++){
                            if(_this.buttons[i].menuUrl.indexOf("update")!=-1){
                                update = true;
                                isShow = true;
                                updatebtn =  true;
                                break;
                            }
                        }

                    }
                });

                if(delbtn||updatebtn){
                    return true;
                }else{
                    return false;
                }

            }
        }
    });


    layui.use(['table','jquery','laypage','util','laydate','form'], function(){
        var table = layui.table;
        var $ = layui.jquery;
        var util = layui.util;
        var laydate = layui.laydate;
        var form = layui.form;
        //监听行单击/双击事件（双击事件为：rowDouble,单击事件为：row，参数为表格lay-filter的值）
        table.on('rowDouble(filter)', function(obj){
            // var _this = this;
            // var data = obj.data;
            // console.log(data);
            // //暂时不清楚layUI怎么给弹出层传值，尝试Vue的:value和v-model都不行，只能用jQuery传值了
            // // $("#orderStatus").val(data.orderStatus);
            // // form.render('select','updateFormFilter');
            // // $("#name").val(data.userAddress.name);
            // form.val('updateFormFilter', {
            //     "orderStatus": data.orderStatus // "name": "value"
            //
            //     ,"name": data.userAddress.name
            //     ,"tel": data.userAddress.tel
            //     ,"addr":data.userAddress.addr
            //     // ,"like[write]": true //复选框选中状态
            //     // ,"close": true //开关状态
            //     // ,"sex": "女"
            //     // ,"desc": "我爱 layui"
            });
        // });

        //加载日期选择插件
        laydate.render({
            elem: '#startDate'
        });
        laydate.render({
            elem: '#endDate'
        });
        //刷新表单
        form.render();
        //监听顶部工具栏事件
        table.on('toolbar(filter)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'insert':
                    layer.msg('添加');
                    break;

                //点击批量删除执行以下代码
                case 'getCheckData':
                    layer.confirm('真的删除行么', function(index){
                        layer.close(index);
                        var data = checkStatus.data;
                        var uids = new Array();
                        for(var i = 0;i < data.length;i++){
                            uids.push(data[i].myorderId);
                        }
                        console.log(uids);
                        var s = JSON.stringify(uids);
                        console.log(s);
                        $.ajax({
                            url:"/houtai/page/order/delete",
                            data:{oid:s},
                            type:"post",
                            dataType:"json",
                            success:function (data) {
                                if(data.message == "success"){
                                    layer.msg("删除成功",{icon: 6});
                                    //重载表格
                                    $(".layui-laypage-btn").click();
                                }else if(data.message == "premissionException"){
                                    location.href = "/houtai/page/exception/NoPremission.html";
                                }else if(data.message == "serverException"){
                                    location.href = "/houtai/page/exception/500.html";
                                }else{
                                    layer.msg("删除失败", {icon: 5});
                                }
                            }
                        })
                    });
                    break;
            };
        });

        //监听每一行工具条
        table.on('tool(filter)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
            console.log(data);
            if(layEvent === 'detail'){//查看
                //do somehing
            } else if(layEvent === 'singleDel'){ //删除
                layer.confirm('真的删除行么', function(index){
                    layer.close(index);
                    //向服务端发送删除指令
                    $.ajax({
                        url:"/houtai/page/order/delete",
                        data:{oid:data.myorderId},
                        type:"post",
                        dataType:"json",
                        success:function (data) {
                            if(data.message == "success"){
                                layer.msg("删除成功",{icon: 6});
                                //重载表格
                                $(".layui-laypage-btn").click();
                            }else if(data.message == "premissionException"){
                                location.href = "/houtai/page/exception/NoPremission.html";
                            }else if(data.message == "serverException"){
                                location.href = "/houtai/page/exception/500.html";
                            }else{
                                layer.msg("删除失败", {icon: 5});
                            }
                        }
                    })
                });
            } else if(layEvent === 'singleUpdate'){ //编辑
                form.val('updateFormFilter', {
                    "orderStatus": data.orderStatus // "name": "value"
                    ,"name": data.userAddress.name
                    ,"tel": data.userAddress.tel
                    ,"addr":data.userAddress.addr
                    ,"myorderId":data.myorderId
                    ,"myorderNumber":data.myorderNumber
                    ,"userId":data.userId
                    ,"orderStatus":data.orderStatus
                    ,"orderTime":timeFormat(data.orderTime)
                    ,"totalPrice":data.totalPrice
                    ,"userAddressId":data.userAddressId
                });

                //开起弹出层
                layer.open({
                    //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    type: 1,
                    title: "修改订单信息",
                    area: ['450px', '400px'],//设置弹出层尺寸

                    content: $("#popUpdateUser")//引用的弹出层的页面层的方式加载修改界面表单
                });
                // 获取表单区域所有值
                var data1 = form.val("updateForm");
            }
        });

        //监听表单提交，上述的submit()中的值为事件过滤器的值
        form.on('submit(updateSubmit)', function(data){
            console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
            console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
            console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });


        //设置搜索框查询条件
        var $ = layui.$, active = {
            reload: function(){
                var demoReload = $('#demoReload');
                var str = $("#serachForm").serialize();
                //执行重载
                table.reload('test', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: {
                        myorderNumber:$("#myorderNumber").val(),
                        username:$("#username").val(),
                        orderStatus:$("#orderStatus").val(),
                        startDate:$("#startDate").val(),
                        endDate:$("#endDate").val()
                    }
                }, 'data');
            }
        };

        //监听搜索框提交按钮
        $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        //监听修改框提交
        form.on('submit(formDemo)', function(data){
            layer.msg(JSON.stringify(data.field));
            return false;
        });
    });
</script>

</body>
</html>